<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getCourseList, createExercise, DifficultyLevel, difficultyLabels, getPaperList } from '../../api/exercise'
import type { ExerciseForm, Paper, BaseResponse, Course } from '../../api/exercise'

const formRef = ref<FormInstance>()
const loading = ref(false)
const courseList = ref<Course[]>([])
const paperList = ref<Paper[]>([])
const isCustomPaper = ref(false)

const form = reactive<ExerciseForm>({
  exerciseType: '',
  exerciseDifficulty: '',
  courseName: '',
  paperTitle: ''
})

const rules = reactive<FormRules>({
  exerciseType: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  exerciseDifficulty: [
    { required: true, message: '请选择题目难度', trigger: 'change' }
  ],
  courseName: [
    { required: true, message: '请选择课程', trigger: 'change' }
  ],
  paperTitle: [
    { required: true, message: '请输入题库名称', trigger: 'blur' }
  ]
})

const exerciseTypes = [
  { label: '选择题', value: '选择题' },
  { label: '判断题', value: '判断题' },
  { label: '简答题', value: '简答题' }
]

const difficultyLevels = Object.values(DifficultyLevel)
  .filter(value => typeof value === 'number')
  .map(value => ({
    label: difficultyLabels[value as DifficultyLevel],
    value: value.toString()
  }))

// 题库选项列表
const paperOptions = computed(() => {
  const options = paperList.value.map(paper => ({
    label: paper.paperTitle,
    value: paper.paperTitle
  }))
  console.log('处理后的题库选项:', options)
  return options
})

// 切换题库输入模式
const togglePaperMode = () => {
  isCustomPaper.value = !isCustomPaper.value
  form.paperTitle = ''
}

// 获取课程列表
const fetchCourseList = async () => {
  try {
    const response = await getCourseList()
    courseList.value = response.data.data
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

// 获取题库列表
const fetchPaperList = async () => {
  try {
    const response = await getPaperList()
    const paperData = response.data as BaseResponse<Paper[]>
    paperList.value = paperData.data
  } catch (error) {
    console.error('获取题库列表失败:', error)
    ElMessage.error('获取题库列表失败')
  }
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        // 发送创建请求
        createExercise(form)
        // 立即提示用户
        ElMessage.success('题目正在生成中，请稍后在题目管理页面查看')
        // 重置表单
        formEl.resetFields()
        loading.value = false
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请重试')
        loading.value = false
      }
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchCourseList()
  fetchPaperList()
})
</script>

<template>
  <div class="create-topic">
    <div class="page-header">
      <h2>创建题目</h2>
      <p class="description">使用AI自动生成题目，支持选择题、判断题和简答题</p>
    </div>

    <el-card class="form-card">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="topic-form"
      >
        <el-form-item label="题目类型" prop="exerciseType">
          <el-select
            v-model="form.exerciseType"
            placeholder="请选择题目类型"
            class="form-select"
          >
            <el-option
              v-for="type in exerciseTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="难度级别" prop="exerciseDifficulty">
          <el-select
            v-model="form.exerciseDifficulty"
            placeholder="请选择难度级别"
            class="form-select"
          >
            <el-option
              v-for="level in difficultyLevels"
              :key="level.value"
              :label="level.label"
              :value="level.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="课程名称" prop="courseName">
          <el-select
            v-model="form.courseName"
            placeholder="请选择课程"
            class="form-select"
            filterable
          >
            <el-option
              v-for="course in courseList"
              :key="course.courseId"
              :label="course.courseName"
              :value="course.courseName"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="题库名称" prop="paperTitle">
          <el-select
            v-if="!isCustomPaper"
            v-model="form.paperTitle"
            placeholder="请选择题库"
            class="form-select">
            <el-option
              v-for="option in paperOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <el-input
            v-else
            v-model="form.paperTitle"
            placeholder="请输入新题库名称"
            class="form-input"
          />
          <div class="button-wrapper">
            <el-button
              type="primary"
              link
              @click="togglePaperMode"
            >
              {{ isCustomPaper ? '选择已有题库' : '新建题库' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleSubmit(formRef)"
          >
            {{ loading ? '生成中...' : '生成题目' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="tips-card">
      <template #header>
        <div class="card-header">
          <h3>使用说明</h3>
        </div>
      </template>
      <ol class="tips-list">
        <li>选择合适的题目类型和难度级别</li>
        <li>从下拉列表中选择已有的课程</li>
        <li>输入或选择题库名称，可以是新建或已有的题库</li>
        <li>点击"生成题目"按钮，等待AI生成题目</li>
        <li>生成完成后，题目会自动保存到对应的题库中</li>
      </ol>
    </el-card>
  </div>
</template>

<style scoped>
.create-topic {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.description {
  color: #606266;
  font-size: 14px;
}

.form-card {
  margin-bottom: 24px;
}

.topic-form {
  max-width: 600px;
  margin: 0 auto;
}

.form-select,
.form-input {
  width: 100%;
}

.tips-card {
  background-color: #f8f9fa;
}

.card-header {
  display: flex;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.tips-list {
  margin: 0;
  padding-left: 20px;
  line-height: 1.8;
  color: #606266;
}

.tips-list li {
  margin-bottom: 8px;
}

.tips-list li:last-child {
  margin-bottom: 0;
}

.button-wrapper {
  margin-top: 10px;
}

.paper-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.paper-input-group .form-select,
.paper-input-group .form-input {
  width: 100%;
}

:deep(.paper-select-dropdown) {
  margin-top: 4px;
  max-height: 300px;
  overflow-y: auto;
}

:deep(.el-select-dropdown) {
  z-index: 3000;
}
</style> 